package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.KillConstants;
import cn.itsource.ymcc.constant.OrderStatusConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.mapper.CourseOrderItemMapper;
import cn.itsource.ymcc.mapper.CourseOrderMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
@RocketMQMessageListener(
        consumerGroup = "CourseOrderDelayCloseConsumer",
        topic = OrderStatusConstants.TOPIC_COURSE_ORDER_DELAY_CLOSE,
        selectorExpression = OrderStatusConstants.TAGS_COURSE_ORDER_DELAY_CLOSE
)
@Slf4j
public class CourseOrderDelayCloseConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private CourseOrderMapper courseOrderMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private CourseOrderItemMapper courseOrderItemMapper;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String orderNo = new String(body, "utf-8");
            CourseOrder courseOrder = courseOrderMapper.selectOne(new LambdaQueryWrapper<CourseOrder>().eq(CourseOrder::getOrderNo, orderNo));

            if(OrderStatusConstants.ORDER_DEFAULT.equals(courseOrder.getStatusOrder())){
                //进行关单  修改自己的状态
                courseOrder.setStatusOrder(OrderStatusConstants.ORDER_OUT_TIME);
                courseOrderMapper.updateById(courseOrder);


                //回滚库存
                List<CourseOrderItem> list = courseOrderItemMapper.selectList(new LambdaQueryWrapper<CourseOrderItem>().eq(CourseOrderItem::getOrderNo, orderNo));
                list.forEach(courseOrderItem -> {
                    redisTemplate.opsForValue().increment(KillConstants.KILL_STORE + courseOrderItem.getCourseId(),courseOrderItem.getCount());
                });

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}